<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="子订单id" prop="id">
        <el-input
            v-model="queryParams.id"
            placeholder="请输入子订单id"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable style="width: 240px">
          <el-option
              v-for="dict in order"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" style="width: 308px">
        <el-date-picker
            v-model="daterangeCreateTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="用户名称" prop="createBy">
        <el-input
            v-model="queryParams.createBy"
            placeholder="请输入用户名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>



    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="子订单id" align="center" prop="id" />
      <el-table-column label="总订单id" align="center" prop="payOrderNo" />
      <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="order" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="订单金额" align="center" prop="totalAmount" sortable/>
      <el-table-column label="实付金额" align="center" prop="realAmount" sortable/>
      <el-table-column label="申请退款时间" align="center" prop="refundTime" width="180" sortable>
        <template #default="scope">
          <span>{{ parseTime(scope.row.refundTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="createTime" width="180" sortable>
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名称" align="center" prop="createBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Info" @click="goToDetail(scope.row.id)" v-hasPermi="['order:order:view']">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="机构id" prop="insId">
          <el-input v-model="form.insId" placeholder="请输入机构id" />
        </el-form-item>
        <el-form-item label="总订单id" prop="payOrderNo">
          <el-input v-model="form.payOrderNo" placeholder="请输入总订单id" />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in order"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态备注" prop="message">
          <el-input v-model="form.message" placeholder="请输入状态备注" />
        </el-form-item>
        <el-form-item label="订单金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入订单金额" />
        </el-form-item>
        <el-form-item label="实付金额" prop="realAmount">
          <el-input v-model="form.realAmount" placeholder="请输入实付金额" />
        </el-form-item>
        <el-form-item label="优惠金额" prop="discountAmount">
          <el-input v-model="form.discountAmount" placeholder="请输入优惠金额" />
        </el-form-item>
        <el-form-item label="支付渠道" prop="payChannel">
          <el-input v-model="form.payChannel" placeholder="请输入支付渠道" />
        </el-form-item>
        <el-form-item label="优惠券id" prop="couponId">
          <el-input v-model="form.couponId" placeholder="请输入优惠券id" />
        </el-form-item>
        <el-form-item label="逻辑删除" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入逻辑删除" />
        </el-form-item>
        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker clearable
                          v-model="form.payTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择支付时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单关闭时间" prop="closeTime">
          <el-date-picker clearable
                          v-model="form.closeTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择订单关闭时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单完成时间" prop="finishTime">
          <el-date-picker clearable
                          v-model="form.finishTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择订单完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申请退款时间" prop="refundTime">
          <el-date-picker clearable
                          v-model="form.refundTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择申请退款时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/order/order";
import { useRouter } from 'vue-router';
import { ref } from 'vue';

const router = useRouter();

const { proxy } = getCurrentInstance();
const { order } = proxy.useDict('order');

const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);
const goToDetail = (id) => {
  router.push({ name: 'OrderDetail', params: { id } });
};

// 暴露 goToDetail 函数
defineExpose({ goToDetail });

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    status: null,
    createTime: null,
    createBy: null,
  },
  rules: {
    userId: [
      { required: true, message: "用户id不能为空", trigger: "blur" }
    ],
    insId: [
      { required: true, message: "机构id不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "订单状态不能为空", trigger: "change" }
    ],
    message: [
      { required: true, message: "状态备注不能为空", trigger: "blur" }
    ],
    totalAmount: [
      { required: true, message: "订单金额不能为空", trigger: "blur" }
    ],
    realAmount: [
      { required: true, message: "实付金额不能为空", trigger: "blur" }
    ],
    discountAmount: [
      { required: true, message: "优惠金额不能为空", trigger: "blur" }
    ],
    delFlag: [
      { required: true, message: "逻辑删除不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建订单时间不能为空", trigger: "blur" }
    ],
    updateTime: [
      { required: true, message: "更新时间不能为空", trigger: "blur" }
    ],
    createBy: [
      { required: true, message: "用户名称不能为空", trigger: "blur" }
    ],
    updateBy: [
      { required: true, message: "处理人不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    insId: null,
    payOrderNo: null,
    status: null,
    message: null,
    totalAmount: null,
    realAmount: null,
    discountAmount: null,
    payChannel: null,
    couponId: null,
    delFlag: null,
    payTime: null,
    closeTime: null,
    finishTime: null,
    refundTime: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改订单";
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除订单编号为"' + _ids + '"的数据项？').then(function() {
    return delOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('order/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

getList();
</script>
